package mspbots.qbd.data.desktop.journal;


import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.qbd.data.BaseReceiver;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

@Log4j2
@Component
@RequiredArgsConstructor
public class JournalsReceiver extends BaseReceiver {


    private final JournalsRepository journalsRepository;

    @RabbitListener(queues = "quick-books-desktop.journal.sync")
    public void processUsers(ObjectNode resultNode) {

        Journals data = Journals.builder().otherId(resultNode.findValue("TxnID").textValue()+"_"+resultNode.findValue("EditSequence").textValue()).build();
        data.setTenantId(resultNode.get("tenantId").longValue());
        ZonedDateTime createdDateTime = ZonedDateTime.parse(resultNode.get("TimeCreated").textValue(),
                DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        ZonedDateTime modifiedDateTime = ZonedDateTime.parse(resultNode.get("TimeModified").textValue(),
                DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        createdDateTime = createdDateTime.withZoneSameInstant(ZoneOffset.UTC);
        modifiedDateTime = modifiedDateTime.withZoneSameInstant(ZoneOffset.UTC);
        data.setCreatedTime(createdDateTime.toLocalDateTime());
        data.setUpdatedTime(modifiedDateTime.toLocalDateTime());
        data.setExtend(resultNode);
        data.setSyncTime(LocalDateTime.now());

        this.journalsRepository.findByOtherIdAndTenantId(data.getOtherId(), data.getTenantId())
                .map(invoices -> {
                    data.setId(invoices.getId());
                    return data;
                }).defaultIfEmpty(data)
                .flatMap(this.journalsRepository::save).block(Duration.ofSeconds(10));

    }
}
